﻿using DataRepositoryLayer.Classes;
using DataRepositoryLayer.Interfaces;
using ModelLayer;
using ModelLayer.DTO;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.Threading;
using System.Diagnostics;

/*****************************************************************************
 * Not really necessary for the moment, only use it if you are going to add
 * some Battery specific function to it. 
 * Otherwise delete alongside with interfaces and just use generic.
 * 
 * **************************************************************************/
namespace DataRepositoryLayer.Classes
{
    public class BatteryRepository : GenericDataRepository<Battery>, IBatteryRepository
    {

        public BatteryRepository(IUnitOfWork unitOfWork)
            : base(unitOfWork)
        {

        }


        public IList<Battery> GetPossibleBatteriesToReserve(IList<PointReservationDTO> desiredReservations, BatteryType desiredType)
        {
            int typeId = desiredType.id;

            String station_ids = desiredReservations.Select(i => i.StationId.ToString()).Aggregate((a, b) => a + ", " + b);
            if (station_ids.EndsWith(","))
            {
                station_ids.Remove(station_ids.Length - 1);
            }

            Debug.WriteLine("station ids => " + station_ids);


            int[] ids = desiredReservations.Select(i => i.StationId).ToArray();

            context.Database.ExecuteSqlCommand(
                String.Format("SELECT NULL FROM Battery WITH(ROWLOCK, UPDLOCK, INDEX(reservation_index)) WHERE station_id IN ({0}) AND battery_type_id = {1}", 
                station_ids, typeId));
            
            return GetList(s => ids.Contains(s.station_id) && s.battery_type_id == typeId);
        }




        public Battery GetByIdForReservation(int id)
        {
            context.Database.ExecuteSqlCommand("SELECT NULL FROM Battery WITH(ROWLOCK, UPDLOCK, INDEX(reservation_index)) WHERE id = " + id);
            return GetSingle(b => b.id == id);
        }
    }
}
